import { HttpRequest } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { BaseInterceptor, DA_SERVICE_TOKEN, ITokenService, JWTTokenModel } from '@delon/auth';
import { _HttpClient } from '@delon/theme';
import { AlainAuthConfig } from '@delon/util';
import { environment } from '@env/environment';

import { CheckJwt } from './helper';

@Injectable()
export class YangJWTInterceptor extends BaseInterceptor {
    private get tokenSrv(): ITokenService {
        return this.injector.get(DA_SERVICE_TOKEN);
    }

    /**
     * 文件上传的地址
     * @private
     */
    private urls: RegExp[] = [/\/resource\/oss\/upload/];

    isAuth(options: AlainAuthConfig): boolean {
        this.model = this.injector.get(DA_SERVICE_TOKEN).get<JWTTokenModel>(JWTTokenModel);
        if (!environment.production) {
            console.log(`%c JWT_START:JWT验证开始`, `background:green; color:#fff`, this.model['time']);
        }
        return CheckJwt(this.model as JWTTokenModel, options.token_exp_offset!);
    }

    setReq(req: HttpRequest<any>, _options: AlainAuthConfig): HttpRequest<any> {
        for (const item of this.urls as RegExp[]) {
            if (item.test(req.url)) {
                return req.clone({
                    setHeaders: {
                        Authorization: `Bearer ${this.model.token}`
                    }
                });
            }
        }
        return req.clone({
            setHeaders: {
                Authorization: `Bearer ${this.model.token}`,
                'Content-Type': 'application/json;charset=UTF-8'
            }
        });
    }
    // 判定token是否在有效期内

    // 判定token是否能刷新
}
